<?php namespace Admin\Common;

/**
 * TODO: VIP API 逻辑层
 * @author pom <pengsuangqi@aomai.com.au>
 */
class POMVIPClient
{
//--------------------------------------------- 以下页面内部调用

  // TODO: 提交到Bean
  // $OrderId:订单主键 ,$UserId：系统当前登陆账号ID
  public function PushOrder($OrderId,$UserId)
  {
    $params = array();
    $params["OrderId"] = $OrderId;
    $params["UserId"]  = $UserId;
    $url = POMNetTools::buildBizUrl("VipWarehouse","PushOrder",$params);
    $res = POMNetTools::getData($url);
     // print_r($res);exit;
    // POMNetTools::fileDebug($res,"");
    if(!isset($res) || empty($res) ) return "网络错误";
    if( 0 != $res["RetCode"] ) return $res["Message"];

    return "";
  }

  // TODO：上传身份证时调用 根据源系统订单号 设置身份证信息
  public function PlaceDeliveryIDCardBySn($SourceOrderSn,$IdcardSysKey,$IdcardNo)
  {
    $params["SourceOrderSn"] = $SourceOrderSn;
    $params["IdcardSysKey"]  = $IdcardSysKey;
    $params["IdcardNo"]      = $IdcardNo;
    $url = POMNetTools::buildBizUrl("VipWarehouse","PlaceDeliveryIDCardBySn",$params);
    $res = POMNetTools::getData($url);

    if(!isset($res) || empty($res) ) return "网络错误";
    if( 0 != $res["RetCode"] ) return $res["Message"];

    return "";
  }
  // TODO: 日常补货采购调用
  /*
  采购拉商品入库 UserId:当前登录系统的用户ID
  [{"GoodsSn":"adfdf","Quantity":100},...] 返回结果 json数据 [{"Good_Sn":"商品货号"，"Price":"当前客户等级价格","GoodNumber":"采购数量","Staute":0,"Content":"入库失败原因"},
  {"Good_Sn":""，"Price":"","GoodNumber":"","Staute":0,"Content":""}] Staute =1 入库成功，=0入库失败 Content 失败的原因
  返回 格式
  array (size=3)
  'RetCode' => int 1
  'Message' => string '公共库中商品货号（adfdf）有些没有库存！' (length=56)
  'Result' => string '' (length=0)
  */
  public function Purchase($GoodsSnAndQuantityJsonStr,$UserId)
  {
    $params["GoodsSnAndQuantityJsonStr"] = $GoodsSnAndQuantityJsonStr;
    $params["UserId"]                    = $UserId;
    $url = POMNetTools::buildBizUrl("VipWarehouse","Purchase",$params);
    $res = POMNetTools::getData($url);
    // POMNetTools::fileDebug($res,"");
    if(!isset($res) || empty($res) ) return false;

    return $res;
  }

  // TODO:提交预订单
  // $title 预订单标题
  // $GoodsJsonStr：[{"GoodsSn":"","price":1.10,"Quantity":100,"Validity":3,"Delivery":"1481697343"},...]
  // Validity 有效期 按月为单位   Delivery预估发货时间
  public function PlaceAdvanceOrder($title,$UserId,$GoodsJsonStr)
  {
    $params["title"]        = $title;
    $params["UserId"]       = $UserId;
    $params["GoodsJsonStr"] = $GoodsJsonStr;
    $url = POMNetTools::buildBizUrl("VipWarehouse","PlaceAdvanceOrder",$params);
    $res = POMNetTools::getData($url);

    if(!isset($res) || empty($res) ) return "网络错误";
    if( 0 != $res["RetCode"] ) return $res["Message"];

    return "";
  }


//--------------------------------------------- 以上页面内部调用

  // TODO: 模拟下单
  public function SimulatePlaceOrder( $params = array() )
  {
    $total = 0;
    $GoodsArrs = json_decode($params["GoodsJsonStr"],true);
    foreach ($GoodsArrs as $key => $value)
      $total += $value["Quantity"];

    $_params["SourceOrderSn"] = $params["SourceOrderSn"];
    $_params["Total"]         = $total;
    $_params["Remark"]        = "测试下单";
    $_params["IsTestOrder"]   = "true";
    $url = POMNetTools::buildBizUrl("GatewayServer","PlaceOrderInfo",$_params);
    $res = POMNetTools::getData($url);
    if(!isset($res) || empty($res) ) return false;
    if( 0 != $res["RetCode"] ) return $res;

    $tmp = json_decode($res["Result"] ,true );
    $OrderId = $tmp["OrderId"];

    $_params1["OrderId"]       = $OrderId;
    $_params1["GoodsJsonStr"]  = $params["GoodsJsonStr"];
    $_params1["IsTestOrder"]   = "true";
    $url = POMNetTools::buildBizUrl("GatewayServer","PlaceOrderGoods",$_params1);
    $res = POMNetTools::getData($url);

    // POMNetTools::fileDebug($res,"");

    if(!isset($res) || empty($res) ) return false;
    if( 0 != $res["RetCode"] ) return $res;

    return $tmp;
  }
  // TODO: 正式下单
  public function RegularPlaceOrder( $params = array() )
  {
    // POMNetTools::fileDebug($params,"");
    $total = 0;
    $GoodsArrs = json_decode($params["GoodsJsonStr"],true);
    foreach ($GoodsArrs as $key => $value)
      $total += $value["Quantity"];

    $_params["SourceOrderSn"] = $params["SourceOrderSn"];
    $_params["Total"]         = $total;
    $_params["Remark"]        = $params["Remark"];

    $url = POMNetTools::buildBizUrl("GatewayServer","PlaceOrderInfo",$_params);
    $res = POMNetTools::getData($url);
    if(!isset($res) || empty($res) ) return false;
    if( 0 != $res["RetCode"] ) return $res;

    $tmp = json_decode($res["Result"] ,true );
    $OrderId = $tmp["OrderId"];

    $_params1["OrderId"]       = $OrderId;
    $_params1["GoodsJsonStr"]  = $params["GoodsJsonStr"];
    $url = POMNetTools::buildBizUrl("GatewayServer","PlaceOrderGoods",$_params1);
    $res = POMNetTools::getData($url);
    // POMNetTools::fileDebug($url,"");
    if(!isset($res) || empty($res) ) return false;
    if( 0 != $res["RetCode"] ) return $res;


    // 提交地址
    $_params2["OrderId"]    = $OrderId;
    $_params2["Consignee"]  = $params["Consignee"];
    $_params2["Address"]    = $params["Address"];
    $_params2["Mobile"]     = $params["Mobile"];
    $_params2["Province"]   = $params["Province"];
    $_params2["City"]       = $params["City"];
    $_params2["District"]   = $params["District"];

    if( !empty($params["Zipcode"]) )     $_params2["Zipcode"]      = $params["Zipcode"];
    if( !empty($params["Tel"]) )         $_params2["Tel"]          = $params["Tel"];
    if( !empty($params["Email"]) )       $_params2["Email"]        = $params["Email"];
    if( !empty($params["Country"]) )     $_params2["Country"]      = $params["Country"];
    if( !empty($params["SignBuilding"])) $_params2["SignBuilding"] = $params["SignBuilding"];

    $url = POMNetTools::buildBizUrl("GatewayServer","PlaceDeliveryAddress",$_params2);
    $res = POMNetTools::getData($url);
    // POMNetTools::fileDebug($res,"");
    if(!isset($res) || empty($res) ) return false;
    if( 0 != $res["RetCode"] ) return $res;

    // 提交身份证信息
    if( /*!empty($params["IdcardSysKey"]) &&*/ !empty($params["IdcardNo"])  )
    {
        $_params3["OrderId"]       = $OrderId;
        $_params3["IdcardSysKey"]  = $params["IdcardSysKey"];
        $_params3["IdcardNo"]      = $params["IdcardNo"];
        $url = POMNetTools::buildBizUrl("GatewayServer","PlaceDeliveryIDCard",$_params3);
        // POMNetTools::fileDebug($params3,"");
        // POMNetTools::fileDebug($url,"");
        $res = POMNetTools::getData($url);
    }

    return $tmp;
  }

  // TODO: 异步设置身份证信息
  public function SetIdCardMsg($SourceOrderSn,$IdcardSysKey,$IdcardNo)
  {
    $params = array();
    // 根据源系统订单号获取ID
    $VIPHand = M('order_info');
    $where["source_order_sn"] = $SourceOrderSn;
    $ret = $VIPHand->where($where)->find();
    if( null == $ret ) return false;
    $params["OrderId"]       = $ret["order_id"];
    $params["IdcardSysKey"]  = $IdcardSysKey;
    $params["IdcardNo"]      = $IdcardNo;
    $url = POMNetTools::buildBizUrl("GatewayServer","PlaceDeliveryIDCard",$params);
    // POMNetTools::fileDebug($url,"");exit;
    $res = POMNetTools::getData($url);
    if(!isset($res) || empty($res) || 0 != $res["RetCode"] ) return false;

    return true;
  }

  public function GetDeliveryInfoForOrderSNAndSoucesysOrderSn( $OrderSn , $SourceOrderSn )
  {
    if( !empty($SourceOrderSn) )
      $OrderSn = $this->GetOrderSnForSoucesysOrderSn($SourceOrderSn);
    if( empty($OrderSn) ) return false;

    $params = array();
    $params["OrderSn"] = $OrderSn;
    $url = POMNetTools::buildBizUrl("GatewayServer","QueryDelivery",array());
    $res = POMNetTools::postData($url,$params);
    if(!isset($res) || empty($res) || 0 != $res["RetCode"] ) return false;

    return json_decode( $res["Result"],true);
  }
  static function GetOrderSnForSoucesysOrderSn( $SourceOrderSn )
  {
    $VIPHand = M('order_info');
    $where["source_order_sn"] = $SourceOrderSn;
    $ret = $VIPHand->where($where)->find();
    if( null != $ret )
    {
      return $ret["order_sn"];
    }
    return "";
  }


  // TODO: 根据快递公司和运单号获取物流公司信息
  public function GetLogisticsInfoForInvoice($InvoiceNo,$ExpresscompanyName){}

  // TODO: 根据 barcode或者goodssn获取 库存
  public function GetStockForGoodsSnOrBarcode($GoodsSn,$BarCode)
  {
    $VIPInfo = $this->GetVipInfo();
    if( false != $VIPInfo )
    {
      if( !empty($BarCode) )
        $GoodsSn = $this->GetGoodsSnForBarCode($BarCode);
      if( empty($GoodsSn) ) return false;

      $ret = array();
      $ret["PRI"] = array();
      $ret["PUB"] = array();

      // 1.获取公共仓库存
      $ret["PUB"] = $this->GetStockPubQuantity($GoodsSn);
      // 2.如果没有找到公共仓的信息  返回失败
      if( null === $ret["PUB"] ) return false;
      // 3.获取VIP虚拟仓库存
      $ret["PRI"] = $this->GetStockPriQuantity($GoodsSn);
      return $ret;
    }

    return false;
  }

  // {"Quantity":1,"Salenumber":1}
  static function GetStockPriQuantity($GoodsSn)
  {
    $ret = array();
    $VIPHand = M('inventory');
    $where["goods_sn"] = $GoodsSn;
    $where["is_deleted"] = 0;
    $tmp = $VIPHand->where($where)->find();
    if( $tmp == null ) return null;

    $ret["Quantity"] = $tmp["quantity"];
    $ret["Salenumber"] = $tmp["salenumber"];
    return $ret;
  }
  static function GetStockPubQuantity($GoodsSn)
  {
    $ret = array();
    $JXCHand = M('vip_inventory','jxc_','JxcDbConfig');
    $where["goods_sn"] = $GoodsSn;
    $where["istype"]   = "PUB";
    $where["is_deleted"] = 0;
    $tmp = $JXCHand->where($where)->find();
    if( $tmp == null ) return null;

    $ret["Quantity"] = $tmp["quantity"];
    $ret["Salenumber"] = $tmp["salenumber"];
    return $ret;
  }


  //TODO: 根据 barcode或者goodssn获取商品价格
  public function GetPriceForGoodsSnOrBarcode($GoodsSn,$BarCode)
  {
    $VIPInfo = $this->GetVipInfo();
    // POMNetTools::fileDebug( $VIPInfo , "");
    if( false != $VIPInfo )
    {
      //TODO: 根据 GoodsSn 获取 BarCode
      if( !empty($BarCode) )
      {
        $GoodsSn = $this->GetGoodsSnForBarCode($BarCode);
        // POMNetTools::fileDebug( $GoodsSn , "");
      }
      if( empty($GoodsSn) ) return -1;

      $params = array();
      $params["GoodsSn"] = $GoodsSn;
      // POMNetTools::$DEBUG=true;
      $url = POMNetTools::buildBizUrl("GatewayServer","QueryGoodsPrice",array());
      $res = POMNetTools::postData($url,$params);
      if(!isset($res) || empty($res) || 0 != $res["RetCode"] ) return -1;

      return $res["Result"];
    }
    return -1;
  }
  //TODO: 根据 GoodsSn 获取 BarCode
  public function GetGoodsSnForBarCode( $BarCode )
  {
    $JXCHand = M('yw_goods','jxc_','JxcDbConfig');
    $where["bar_code"] = $BarCode;
    $ret = $JXCHand->where($where)->find();
    if( null != $ret )
    {
      return $ret["goods_sn"];
    }
    return "";
  }

  //TODO: 根据 GoodsSn 获取 BarCode goods_name
  public  function GetGoodsSnForBarCodeAndGoodsName( $GoodsSn )
  {
    $JXCHand = M('yw_goods','jxc_','JxcDbConfig');
    $where["goods_sn"] = $GoodsSn;
    $ret = $JXCHand->where($where)->find();
    $data = array('bar_code'=>$ret['bar_code'],'goods_name'=>$ret['goods_name']);
    if( null != $ret )
    {
      return $data;
    }
    return "";
  }

  //TODO: 获取VIP的信息  等级  余额  等
  public function GetVipInfo()
  {
    $params = array();
    $url = POMNetTools::buildBizUrl("VipWarehouse","GetAccountInfo",$params);
    $res = POMNetTools::getData($url);
    if(!isset($res) || empty($res) || 0 != $res["RetCode"] ) return false;
    // {"VipId":2,"Balance":300}
    // 返回VIPID 余额  等级
    $ret = array();
    $ret = json_decode( $res["Result"] , true);
    $ret["Grade"] = $this->GetVipGradeForId($ret["VipId"]);
    return $ret;
  }

  // TODO: 根据VIPID获取等级
  public function GetVipGradeForId($VIPId)
  {

    $JXCHand = M('vip_customer','jxc_','JxcDbConfig');
    $where["vip_id"]     = $VIPId;
    $where["is_deleted"] = 0;
    $ret = $JXCHand->where($where)->find();

    if( null != $ret )
    {
        $JXCHand = M('vip_customer_class','jxc_','JxcDbConfig');
        $where["id"]         = $ret["vip_type"];
        $where["is_deleted"] = 0;
        $tmp = $JXCHand->where($where)->find();
        if (null != $tmp)
        {
            if ($tmp['code'] == "VIP_Fifth_Price" ) return 5;
            if ($tmp['code'] == "VIP_Fourth_Price") return 4;
            if ($tmp['code'] == "VIP_First_Price")  return 1;
            if ($tmp['code'] == "VIP_Second_Price") return 2;
            if ($tmp['code'] == "VIP_Third_Price")  return 3;
        }
    }
    return 1;
  }

  public function initOAuth()
  {
    $params = array();
    $url = POMNetTools::buildBizUrl("VipWarehouse","InitOauth",$params);
    $res = POMNetTools::getData($url);
    if(!isset($res) || empty($res) || 0 != $res["RetCode"] ) return false;
    return true;
  }

  public function getAppSecretForKey($APPkeY)
  {
    $OAuthHand = M("oauth");
    $where["app_key"]    = $APPkeY;
    $where["is_deleted"] = 0;
    $ret = $OAuthHand->where($where)->find();
    if($ret != null ) return $ret["app_secret"];
    return false;
  }



//采购验证当前用户余额 sum_price当前所需花费的金额
  public function checkUserMoney($sum_price = 0)
  {
      $list = D('cash_transaction')->field('surplus')->order('id desc')->find();
      if(empty($list)){
        return false;
      }
      $user_money =  $list['surplus'];
      //最小余额
      $min_money = C('MINIMUM_MONEY');
/*        return ($user_money-$sum_price);exit;*/
      if( ($user_money-$sum_price)>$min_money){
        return true;
      }
      return false;
  }


  //中文搜索商品
  //$str = 美赞臣安婴妈妈,5456asdasdaa,奶粉 ;
  public function  SearchChineseGoods($str){
      if($str!=''){

         // $url = "http://web_aomai_51m.com/api/start_check.php?act=search_chinese_goods_name&data=". urlencode($str);
        $url = "http://www.51m.com.au/api/start_check.php?act=search_chinese_goods_name&data=". urlencode($str);
         $res = POMNetTools::getData( $url);
         if(!empty($res)){
           return $res;
         }
      }
  }



    //goods_sn 获取商品中文名
  //$str = sn123,sn321,sn444 ;
  public function  GoodsSnGetChineseGoodsName($str){
      if($str!=''){
         $url = "http://web_aomai_51m.com/api/start_check.php?act=goods_sn_get_chinese_goods_name&data=". urlencode($str);
         $res = POMNetTools::getData( $url);
         if(!empty($res)){
           return $res;
         }
      }
  }
}
